package com.ruoyi.project.wechatprogram.ordermaster.controller;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.config.service.IConfigService;
import com.ruoyi.project.wechatprogram.wxuser.domain.WxUser;
import com.ruoyi.project.wechatprogram.wxuser.service.IWxUserService;
import com.ruoyi.project.wechatprogram.moneyoperatelog.domain.WxMoneyOperateLog;
import com.ruoyi.project.wechatprogram.moneyoperatelog.service.IWxMoneyOperateLogService;
import com.ruoyi.project.wechatprogram.ordermaster.domain.WxOrderMaster;
import com.ruoyi.project.wechatprogram.ordermaster.service.IWxOrderMasterService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 餐品订单Controller
 *
 * @author sxchen
 * @date 2020-04-15
 */
@Controller
@RequestMapping("/wechatprogram/ordermaster")
public class WxOrderMasterController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(WxOrderMasterController.class);

    private String prefix = "wechatprogram/ordermaster";
    private Integer operate_type = 1;
    private Integer success = 0;

    @Autowired
    private IWxOrderMasterService wxOrderMasterService;

    @Autowired
    private IWxUserService wxUserService;

    @Autowired
    private IConfigService configService;

    @Autowired
    private IWxMoneyOperateLogService wxMoneyOperateLogService;


    @RequiresPermissions("wechatprogram:ordermaster:view")
    @GetMapping()
    public String ordermaster() {
        return prefix + "/ordermaster";
    }

    /**
     * 查询餐品订单列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WxOrderMaster wxOrderMaster) {
        startPage();
        List<WxOrderMaster> list = wxOrderMasterService.selectWxOrderMasterList(wxOrderMaster);

        return getDataTable(list);
    }

    /**
     * 查询餐品订单列表
     */
    @PostMapping("/listOrder")
    @ResponseBody
    public TableDataInfo listOrder(WxOrderMaster wxOrderMaster) {
        startPage();
        List<WxOrderMaster> list = wxOrderMasterService.selectWxOrderMasterListOrder(wxOrderMaster);

        return getDataTable(list);
    }

    /**
     * 导出餐品订单列表
     */
    @RequiresPermissions("wechatprogram:ordermaster:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WxOrderMaster wxOrderMaster) {
        List<WxOrderMaster> list = wxOrderMasterService.selectWxOrderMasterList(wxOrderMaster);
        ExcelUtil<WxOrderMaster> util = new ExcelUtil<WxOrderMaster>(WxOrderMaster.class);
        return util.exportExcel(list, "ordermaster");
    }

    /**
     * 新增餐品订单
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存餐品订单
     */
    @Log(title = "餐品订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(String remarks, String payId, String buyerName, String buyerPhone, Integer wxUserId, Integer orderStatus,
                              Integer payStatus, Integer orderNum, Integer orderPrice, String repastStartTime,
                              String repastEndTime, String day, String items, Integer categoryType) throws ParseException {
        // 查找用户是否存在
        WxUser wxUser = new WxUser();
        wxUser.setIphone(buyerPhone);
        WxUser wxUserByUser = wxUserService.selectWxUserByUser(wxUser);
        if (wxUserByUser == null) {
            return AjaxResult.error("用户不存在！");
        }
        // 判断是否可以点餐
        String configKey = configService.selectConfigByKey("wx.ordering.deadline.conf");
        // 获取当前小时数
        SimpleDateFormat simpleDate = new SimpleDateFormat("H");
        SimpleDateFormat simpleDate1 = new SimpleDateFormat("yyyy-MM-dd");
        String hour = simpleDate.format(new Date());
        //获取时间加一天
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);//设置起时间
        cal.add(Calendar.DATE, 1);//增加一天
        String time = simpleDate1.format(cal.getTime());
        // String转日期
        Date dayBefore = simpleDate1.parse(time);
        Date dayAfter = simpleDate1.parse(day);
        if (!(Integer.parseInt(hour) < Integer.parseInt(configKey) || dayBefore.before(dayAfter))){
            return AjaxResult.error("该时间段不能点餐，点餐截止时间为" + Integer.parseInt(configKey) + ":00！");
        }
        //查询订单是否重复
        WxOrderMaster wxOrder = new WxOrderMaster();
        wxOrder.setDay(day);
        wxOrder.setBuyerPhone(buyerPhone);
        wxOrder.setCategoryType(categoryType);
        wxOrder.setOrderStatus(WxOrderMaster.ORDER_STATUS_WAIT);
        wxOrder.setPayStatus(WxOrderMaster.PAY_STATUS_YES);

        WxOrderMaster order = wxOrderMasterService.selectWxOrderMasterOrderIsRepeat(wxOrder);
        if (!StrUtil.isBlankIfStr(order)) {
            return AjaxResult.error("请勿重复下单！！！");
        }
        try {
            WxOrderMaster wxOrderMaster = new WxOrderMaster();
            wxOrderMaster.setRemark(remarks);
            wxOrderMaster.setOrderId(payId);
            wxOrderMaster.setBuyerName(buyerName);
            wxOrderMaster.setBuyerPhone(buyerPhone);
            wxOrderMaster.setWxUserId(wxUserId);
            wxOrderMaster.setOrderStatus(orderStatus);
            wxOrderMaster.setPayStatus(payStatus);
            wxOrderMaster.setOrderNum(orderNum);
            wxOrderMaster.setOrderPrice(orderPrice);
            // 设置创建时间
            wxOrderMaster.setCreateTime(new Date());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            wxOrderMaster.setRepastStartTime(simpleDateFormat.parse(repastStartTime));
            wxOrderMaster.setRepastEndTime(simpleDateFormat.parse(repastEndTime));
            wxOrderMaster.setDay(day);
            wxOrderMaster.setCategoryType(categoryType);
            wxOrderMasterService.insertWxOrderMaster(wxOrderMaster, items);
            // 判断余额
            if (wxUserByUser.getBalance() < orderPrice) {
                log.debug("余额不足！");
                return AjaxResult.error("余额不足！");
            }
            // 更新用户金额
            WxUser updateWxUser = new WxUser();
            updateWxUser.setId(wxUserId);
            updateWxUser.setBalance(wxUserByUser.getBalance() - orderPrice);
            Integer successStatus = wxUserService.updateWxUserBalance(updateWxUser);
            if (successStatus <= 0) {
                log.error("更新失败，数据为：" + wxUserByUser.toString());
                return AjaxResult.error("更新失败!");
            }
            // 更新成功后将用户数据重新返回到前端做展示
            WxUser wxUserResult = new WxUser();
            wxUserResult.setIphone(buyerPhone);
            //添加金额变动记录
            WxMoneyOperateLog moneyOperateLog = new WxMoneyOperateLog();
            moneyOperateLog.setUserId(wxUserByUser.getId());
            moneyOperateLog.setIphone(wxUserByUser.getIphone());
            moneyOperateLog.setName(wxUserByUser.getName());
            moneyOperateLog.setType(operate_type);
            moneyOperateLog.setBalanceChange(orderPrice);
            moneyOperateLog.setBalance(wxUserByUser.getBalance() - orderPrice);
            moneyOperateLog.setDescription("点餐消费");
            wxMoneyOperateLogService.insertWxMoneyOperateLog(moneyOperateLog);
            return AjaxResult.success(wxUserService.selectWxUserByUser(wxUserResult));
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        return AjaxResult.success();
    }

    /**
     * 修改餐品订单
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap) {
        WxOrderMaster wxOrderMaster = wxOrderMasterService.selectWxOrderMasterById(id);
        mmap.put("wxOrderMaster", wxOrderMaster);
        return prefix + "/edit";
    }

    @Log(title = "餐品订单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WxOrderMaster wxOrderMaster) {

        // 判断是否取消订单
        if (wxOrderMaster.getOrderStatus().equals(WxOrderMaster.ORDER_STATUS_CANCEL)) {
            AjaxResult ajaxResult = wxOrderMasterService.updateWxOrderMaster(wxOrderMaster);

            return ajaxResult;
        }
        return AjaxResult.error("严重未知异常！");
    }

    /**
     * 删除餐品订单
     */
    @RequiresPermissions("wechatprogram:ordermaster:remove")
    @Log(title = "餐品订单", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(wxOrderMasterService.deleteWxOrderMasterByIds(ids));
    }


}
